package com.jfplugin.kit.mockrender;

import java.io.IOException;
import java.lang.reflect.Proxy;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jfinal.render.Render;
import com.jfinal.render.RenderManager;
import com.jfplugin.kit.mockrender.mockhttp.MockHttpServletRequest;
import com.jfplugin.kit.mockrender.mockhttp.MockHttpServletResponse;

/**
 * 虚拟RenderKit
 * 
 * @author farmer
 *
 */
public class MockRenderKit {

	/**
	 * 渲染
	 * @param render
	 * @return
	 */
	public static String render(Render render) {
		HttpServletRequest request = (HttpServletRequest) Proxy
				.newProxyInstance(MockRenderKit.class.getClassLoader(),
						new Class[] { HttpServletRequest.class },
						new MockHttpServletRequest());
		return render(render, request);
	}
	
	/**
	 * 渲染
	 * @param render
	 * @param dataMap
	 * @return
	 */
	public static String render(Render render, Map<String, Object> dataMap) {
		HttpServletRequest request = (HttpServletRequest) Proxy
				.newProxyInstance(MockRenderKit.class.getClassLoader(),
						new Class[] { HttpServletRequest.class },
						new MockHttpServletRequest());
		for (Map.Entry<String, Object> entry : dataMap.entrySet()) {
			request.setAttribute(entry.getKey(), entry.getValue());
		}
		return render(render, request);
	}
	
	
	/**
	 * 渲染
	 * @param render
	 * @param request
	 * @return
	 */
	public static String render(Render render, HttpServletRequest request) {
		HttpServletResponse response = (HttpServletResponse) Proxy
				.newProxyInstance(MockRenderKit.class.getClassLoader(),
						new Class[] { HttpServletResponse.class },
						new MockHttpServletResponse());
		render.setContext(request, response).render();
		try {
			return response.getWriter().toString();
		} catch (IOException e) {
			throw new RuntimeException("模板渲染异常！", e);
		}
	}
	
	/**
	 * 渲染模板
	 * 
	 * @param viewPath
	 *            模板路径
	 * @param dataMap
	 *            数据
	 * @return 返回渲染结果
	 */
	public static String render(String viewPath, Map<String, Object> dataMap) {
		HttpServletRequest request = (HttpServletRequest) Proxy
				.newProxyInstance(MockRenderKit.class.getClassLoader(),
						new Class[] { HttpServletRequest.class },
						new MockHttpServletRequest());
		for (Map.Entry<String, Object> entry : dataMap.entrySet()) {
			request.setAttribute(entry.getKey(), entry.getValue());
		}
		return render(viewPath, request);
	}

	/**
	 * 渲染模板
	 * @param viewPath
	 * 			模板路径
	 * @param request
	 * 			request
	 * @return	返回渲染结果
	 */
	public static String render(String viewPath, HttpServletRequest request) {
		return render(RenderManager.me().getRenderFactory().getRender(viewPath), request);
	}
}
